#!/usr/bin/env node
const mysql = require('mysql2/promise');

(async () => {
  try {
    const {
      MYSQL_HOST = '8.149.243.80',  // 云服务器公网IP
      MYSQL_PORT = '3307',
      MYSQL_USER = 'root',
      MYSQL_PASSWORD = '123456',
      MYSQL_DATABASE = 'mqtt_app'
    } = process.env;

    // 简单交互确认（可通过环境变量 CLEAR_DB_CONFIRM=yes 跳过）
    if ((process.env.CLEAR_DB_CONFIRM || '').toLowerCase() !== 'yes') {
      console.error('保护: 设置环境变量 CLEAR_DB_CONFIRM=yes 才会执行清空操作');
      process.exit(1);
    }

    const connection = await mysql.createConnection({
      host: MYSQL_HOST,
      port: Number(MYSQL_PORT),
      user: MYSQL_USER,
      password: MYSQL_PASSWORD,
      database: MYSQL_DATABASE,
      multipleStatements: true,
      connectTimeout: 10_000
    });

    // 关闭外键检查，truncate 所有非系统表，再恢复外键检查
    const [rows] = await connection.query(
      'SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = "BASE TABLE"',
      [MYSQL_DATABASE]
    );

    const tableNames = rows.map(r => r.TABLE_NAME || r.table_name);
    if (tableNames.length === 0) {
      console.log('数据库中没有可清空的数据表');
      await connection.end();
      process.exit(0);
    }

    await connection.query('SET FOREIGN_KEY_CHECKS=0');
    for (const table of tableNames) {
      const sql = `TRUNCATE TABLE \`${table}\``;
      await connection.query(sql);
      console.log(`已清空: ${table}`);
    }
    await connection.query('SET FOREIGN_KEY_CHECKS=1');

    await connection.end();
    console.log('数据库清空完成（仅清数据，未改表结构）。');
    process.exit(0);
  } catch (err) {
    console.error('清空数据库失败:', err.message);
    process.exit(2);
  }
})();
